package com.sqbang.dbcompare.listener;

import com.sqbang.dbcompare.constant.SystemConstant;
import com.sqbang.dbcompare.pojo.cache.CommonData;
import com.sqbang.dbcompare.pojo.dto.DatabaseInfoDto;
import com.sqbang.dbcompare.util.Tools;
import lombok.extern.log4j.Log4j2;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;

import java.net.InetAddress;
import java.util.List;

/**
 * 应用启动监听类
 *
 * @author suqiongbang
 * @date 2021/12/14 11:14
 */
@Log4j2
public class StartListener implements ApplicationListener<ContextRefreshedEvent> {

    @Override
    public void onApplicationEvent(ContextRefreshedEvent event) {
        try {
            // 读取系统保存的数据
            Object databaseInfoData = Tools.getCacheData(SystemConstant.FilePath.DATABASE_INFO_DATA_FILE_NAME);
            if (databaseInfoData != null) {
                CommonData.databaseInfoList = (List<DatabaseInfoDto>) databaseInfoData;
            }
            Object ignoreSpellingWordsData = Tools.getCacheData(SystemConstant.FilePath.IGNORE_SPELLING_WORDS_DATA_FILE_NAME);
            if (ignoreSpellingWordsData != null) {
                CommonData.ignoreSpellingWordStr = (String) ignoreSpellingWordsData;
            }
            Object ignorePluralizeWordsData = Tools.getCacheData(SystemConstant.FilePath.IGNORE_PLURALIZE_WORDS_DATA_FILE_NAME);
            if (ignorePluralizeWordsData != null) {
                CommonData.ignorePluralizeWordStr = (String) ignorePluralizeWordsData;
            }
            // 生成验证码
            CommonData.authCode = Tools.getRandomCode();

            // 打开浏览器
            InetAddress localHost = InetAddress.getLocalHost();
            String localIp = localHost.getHostAddress();
            String url = String.format("http://%s:%s/auth.html?authCode=%s", localIp, "8280", CommonData.authCode);
            log.info("项目源码地址[https://gitee.com/sqbang/open-database-compare]");
            log.info(String.format("本地访问地址[%s]", url));
            log.info(String.format("访问的授权码[%s]", CommonData.authCode));
            if (Tools.isWindows()) {
                Runtime.getRuntime().exec("cmd /c start " + url);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}